#!/bin/sh

set -u # Treat unset variables as an error.

WEB_CERTS="/config/certs/web-privkey.pem /config/certs/web-fullchain.pem"
VNC_CERTS="/config/certs/vnc-privkey.pem /config/certs/vnc-fullchain.pem"

RUN_DIR=/var/run/certsmonitor

WEB_CERTS_HASH_FILE="${RUN_DIR}"/web_certs_hash
VNC_CERTS_HASH_FILE="${RUN_DIR}"/vnc_certs_hash

hash() {
    stat -c '%n %s %Y' "$@" | md5sum | cut -d' ' -f1
}

restart_nginx() {
    echo "Restarting nginx..."
    /usr/sbin/nginx -s reload
}

restart_xvnc() {
    echo "Restarting Xvnc..."
    killall Xvnc
}

[ -d "${RUN_DIR}" ] || mkdir --mode=755 "${RUN_DIR}"

# Get previous hashes.
WEB_CERTS_HASH="$(cat "${WEB_CERTS_HASH_FILE}" 2> /dev/null || true)"
VNC_CERTS_HASH="$(cat "${VNC_CERTS_HASH_FILE}" 2> /dev/null || true)"

# Get new hashes.
WEB_CERTS_NEW_HASH="$(eval "set -- ${WEB_CERTS}" && hash "$@")"
VNC_CERTS_NEW_HASH="$(eval "set -- ${VNC_CERTS}" && hash "$@")"

update_hashes=0

if [ -n "${WEB_CERTS_HASH}" ] && [ -n "${VNC_CERTS_HASH}" ]; then
    # Restart nginx if certificates changed.
    if [ "${WEB_CERTS_NEW_HASH}" != "${WEB_CERTS_HASH}" ]; then
        echo "Web certificates changed."
        update_hashes=1
        restart_nginx
    fi

    # Restart xvnc if certificates changed.
    if [ "${VNC_CERTS_NEW_HASH}" != "${VNC_CERTS_HASH}" ]; then
        echo "VNC certificates changed."
        update_hashes=1
        restart_xvnc
    fi
else
    update_hashes=1
fi

# Save new hashes.
if [ "${update_hashes}" -eq 1 ]; then
    echo "${WEB_CERTS_NEW_HASH}" > "${WEB_CERTS_HASH_FILE}"
    echo "${VNC_CERTS_NEW_HASH}" > "${VNC_CERTS_HASH_FILE}"
fi

# vim:ft=sh:ts=4:sw=4:et:sts=4
